package com.gateway.router.resilience4j.factory;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import io.github.resilience4j.timelimiter.TimeLimiterRegistry;
import org.springframework.cloud.circuitbreaker.resilience4j.ReactiveResilience4JCircuitBreakerFactory;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/25 09:06
 **/
public final class Resilience4JRegistryFactory {

    private static volatile Resilience4JRegistryFactory INSTANCE;

    private final CircuitBreakerRegistry circuitBreakerRegistry;
    private final TimeLimiterRegistry timeLimiterRegistry;

    private Resilience4JRegistryFactory(ReactiveResilience4JCircuitBreakerFactory factory) {
        this.circuitBreakerRegistry = factory.getCircuitBreakerRegistry();
        this.timeLimiterRegistry = factory.getTimeLimiterRegistry();
    }

    public static void newInstance(ReactiveResilience4JCircuitBreakerFactory factory) {
        if (INSTANCE == null) {
            synchronized (Resilience4JRegistryFactory.class) {
                INSTANCE = new Resilience4JRegistryFactory(factory);
            }
        }
    }

    public CircuitBreakerRegistry getCircuitBreakerRegistry() {
        return circuitBreakerRegistry;
    }

    public TimeLimiterRegistry getTimeLimiterRegistry() {
        return timeLimiterRegistry;
    }

    public static Resilience4JRegistryFactory getInstance() {
        return INSTANCE;
    }

    public static void addConfig(String key, CircuitBreakerConfig config) {
        getInstance().getCircuitBreakerRegistry().addConfiguration(key, config);
    }

    public static void addConfig(String key, TimeLimiterConfig config) {
        getInstance().getTimeLimiterRegistry().addConfiguration(key, config);
    }

    public static void remove(String key) {
        getInstance().getCircuitBreakerRegistry().remove(key);
        getInstance().getTimeLimiterRegistry().remove(key);
    }
}
